今天要做得看似跟第16天的很像,其實還是有點差異啦,可以說是第16天的強化版!
開始前我們先來比對一下差異
| 比較 | Day 16靜態內建 Prompt 字典 | Day 27動態持久化使用者字典 |
|---|---|---|
| 資料來源 | Hardcoded(寫死在程式碼中),開發時固定 | 使用者操作與本地資料庫,例如 SharedPreferences / Hive |
| 修改彈性 | 無法動態新增;若要加入新團體或偶像暱稱,必須修改 Dart 程式碼並重新發布 App | 可隨時新增、修改或刪除專有名詞,立即生效 |
| Prompt 產生機制 | 使用固定的靜態字串,例如韓日流行語範例 | 每次發送 API 請求前,即時讀取資料庫,並以 StringBuffer / String Interpolation 動態組裝 Prompt |
| 應用場景 | 通用韓日語網路俚語,例如「草」、「無理」、「억까」 | 客製化的偶像個人專有名詞,例如 레이 ➔怜 |
修改 lib/features/live_translate/data/models/slang_translation_prompt.dart,加入 customWords 參數,將字典轉為專屬對照表格式
import 'fandom_word.dart';
class SlangTranslationPrompt {
static String buildSystemPrompt({
required String targetLanguage,
List<FandomWord> customWords = const [],
}) {
// 將自訂單字格式化為 Prompt 清單
final StringBuffer dictionaryBuffer = StringBuffer();
if (customWords.isNotEmpty) {
dictionaryBuffer.writeln('\n【使用者指定專有名詞與暱稱對照表(最高優先級)】:');
for (var word in customWords) {
dictionaryBuffer.writeln('- ${word.original} ➔ ${word.translated}');
}
}
return '''你是一位精通韓日流行文化、偶像飯圈與網路社群用語的同聲傳譯專家。請將輸入的語音逐字稿翻譯為 $targetLanguage。
${dictionaryBuffer.toString()}
【核心翻譯原則】:
1. 優先使用上述【對照表】中的譯名與暱稱,確保偶像姓名與專有名詞翻譯 100% 精準。
2. 精準識別韓日語流行語、縮寫、網路梗(如:草生える, 尊い, 無理, 推し活),並轉譯為台灣自然流暢的流行用語(如:笑死、尊爆)。
3. 保持直播口語感,自動補齊標點符號並剔除「呃、那個」等無意義發聲。
4. 僅回傳最終翻譯結果,嚴禁包含任何額外說明。''';
}
}
TranslationService 自動載入最新字典修改 lib/features/live_translate/data/services/translation_service.dart,在翻譯時從 DictionaryService 抓取最新詞條
import 'dictionary_service.dart';
import '../models/slang_translation_prompt.dart';
class TranslationService {
final DictionaryService _dictionaryService = DictionaryService();
Future<String> translateText({
required String rawText,
String targetLanguage = '繁體中文',
}) async {
// 1. 動態讀取本地最新的自訂字典
final customWords = await _dictionaryService.getWords();
// 2. 建構注入自訂字典後的 System Prompt
final systemPrompt = SlangTranslationPrompt.buildSystemPrompt(
targetLanguage: targetLanguage,
customWords: customWords,
);
// 3. 發送至 LLM API (例如 GPT-4o-mini)
final response = await http.post(
Uri.parse('https://api.openai.com/v1/chat/completions'),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $apiKey',
},
body: jsonEncode({
'model': 'gpt-4o-mini',
'messages': [
{'role': 'system', 'content': systemPrompt},
{'role': 'user', 'content': rawText},
],
'temperature': 0.3, // 保持翻譯穩定度
}),
);
// ... 解析並回傳翻譯結果 ...
return extractTranslationResult(response.body);
}
}